const cfg = require("./config.js");
/****************************** 格式化 ******************************/
// 时间戳转时间
export const timestampToTime = timestamp => {
	function add0(m) {
		return m < 10 ? "0" + m : m;
	}
	//shijianchuo是整数，否则要parseInt转换
	var time = new Date(timestamp);
	var y = time.getFullYear();
	var m = time.getMonth() + 1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	return y + "-" + add0(m) + "-" + add0(d) + " " + add0(h) + ":" + add0(mm);
};
// 时间戳转时间 不要时分秒
export const timestampToTimeNoHour = timestamp => {
	function add0(m) {
		return m < 10 ? "0" + m : m;
	}
	//shijianchuo是整数，否则要parseInt转换
	var time = new Date(timestamp);
	var y = time.getFullYear();
	var m = time.getMonth() + 1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	return y + "-" + add0(m) + "-" + add0(d);
};

export const formatTime = date => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();

	return (
		[year, month, day].map(formatNumber).join("/") +
		" " +
		[hour, minute, second].map(formatNumber).join(":")
	);
};

export const formatNumber = n => {
	n = n.toString();
	return n[1] ? n : "0" + n;
};

/** 格式化数字，不足长度时补0 */
export const formatVal = function(val, formatLen) {
	val = val + "";
	for (var i = val.length; i < formatLen; i++) {
		val = "0" + val;
	}
	return val;
};
/** 限制只能输入数字数 */
export const inputLimitNum = numStr => {
	numStr = numStr.replace(/^(\-)?(\d+)(\.\d{2}).*$/, "$1$2$3");
	numStr = numStr.replace(/[\u4e00-\u9fa5]+/g, ""); //清除汉字
	numStr = numStr.replace(/[^\d.]/g, ""); //清楚非数字和小数点
	numStr = numStr.replace(/^\./g, ""); //验证第一个字符是数字而不是
	numStr = numStr
		.replace(".", "$#$")
		.replace(/\./g, "")
		.replace("$#$", "."); //只保留第一个小数点, 清除多余的

	return numStr;
};
/** 限制只能输入数字以及小数2位 */
export const inputLimitDecimal = numStr => {
	numStr = inputLimitNum(numStr);
	numStr = numStr.match(/\d+(\.\d{0,2})?/)
		? numStr.match(/\d+(\.\d{0,2})?/)[0]
		: "";
	return numStr;
};
/** 将字符串转换成日期 */
export const dateParse = function(dateStr, format) {
	format = format ? format : "yyyy-MM-dd HH:mm:ss";
	var date = new Date();
	var year =
		format.indexOf("yyyy") >= 0
			? dateStr.substr(format.indexOf("yyyy"), 4)
			: date.getFullYear();
	var month =
		format.indexOf("MM") >= 0
			? dateStr.substr(format.indexOf("MM"), 2)
			: date.getMonth() + 1;
	var day =
		format.indexOf("dd") >= 0
			? dateStr.substr(format.indexOf("dd"), 2)
			: date.getDate();
	var hour =
		format.indexOf("HH") >= 0
			? dateStr.substr(format.indexOf("HH"), 2)
			: date.getHours();
	var minute =
		format.indexOf("mm") >= 0
			? dateStr.substr(format.indexOf("mm"), 2)
			: date.getMinutes();
	var second =
		format.indexOf("ss") >= 0
			? dateStr.substr(format.indexOf("ss"), 2)
			: date.getSeconds();
	return new Date(year, month - 1, day, hour, minute, second);
};

/** 将日期转换成字符串 */
export const dateToStr = function(date, format) {
	format = format ? format : "yyyy-MM-dd HH:mm:ss";
	date = date ? date : new Date();
	var dateStr = format.replace("yyyy", date.getFullYear());
	dateStr = dateStr.replace("MM", this.formatVal(date.getMonth() + 1, 2));
	dateStr = dateStr.replace("dd", this.formatVal(date.getDate(), 2));

	dateStr = dateStr.replace("HH", this.formatVal(date.getHours(), 2));
	dateStr = dateStr.replace("mm", this.formatVal(date.getMinutes(), 2));
	dateStr = dateStr.replace("ss", this.formatVal(date.getSeconds(), 2));
	return dateStr;
};

/** 将日期字符串转换成数字字符串 2018-01或2018-01-02 */
export const dateStrToNumStr = function(dateStr, dateStrFormat, format) {
	var date = this.dateParse(dateStr, dateStrFormat);
	return this.dateToStr(date, format);
};

/************ base64 解码 ***********/
export const base64_decode = input => {
	// 解码，配合decodeURIComponent使用
	var base64EncodeChars =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;
	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	while (i < input.length) {
		enc1 = base64EncodeChars.indexOf(input.charAt(i++));
		enc2 = base64EncodeChars.indexOf(input.charAt(i++));
		enc3 = base64EncodeChars.indexOf(input.charAt(i++));
		enc4 = base64EncodeChars.indexOf(input.charAt(i++));
		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;
		output = output + String.fromCharCode(chr1);
		if (enc3 != 64) {
			output = output + String.fromCharCode(chr2);
		}
		if (enc4 != 64) {
			output = output + String.fromCharCode(chr3);
		}
	}
	return utf8_decode(output);
};

export function utf8_decode(utftext) {
	// utf-8解码
	var string = "";
	let i = 0;
	let c = 0;
	let c1 = 0;
	let c2 = 0;
	while (i < utftext.length) {
		c = utftext.charCodeAt(i);
		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		} else if (c > 191 && c < 224) {
			c1 = utftext.charCodeAt(i + 1);
			string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
			i += 2;
		} else {
			c1 = utftext.charCodeAt(i + 1);
			c2 = utftext.charCodeAt(i + 2);
			string += String.fromCharCode(
				((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63)
			);
			i += 3;
		}
	}
	return string;
}
// 过滤html标签
export const htmlDecodeByRegExp = str => {
	var s = "";
	if (str.length == 0) return "";
	s = str.replace(/&amp;/g, "&");
	s = s.replace(/\\r\\n/g, "#r#n");
	s = s.replace(/#r#n/g, "\r\n");
	s = s.replace(/&lt;/g, "<");
	s = s.replace(/&gt;/g, ">");
	s = s.replace(/&nbsp;/g, " ");
	s = s.replace(/&#39;/g, "'");
	s = s.replace(/&quot;/g, '"');
	s = s.replace(/&#xD;/g, "\r");
	s = s.replace(/&#xA;/g, "\n");
	s = s.replace(/<br>/g, "\n");
	// s = s.replace(/<[^>]+>/g,"");
	s = s.replace(/&amp;/g, "");
	s = s.replace(/nbsp;/g, "");
	return s;
};
//保留两位小数

// 生成32位的随机字符串
export const createNonce32CharStr = num => {
	var str = "",
		range = 32,
		arr = [
			"0",
			"1",
			"2",
			"3",
			"4",
			"5",
			"6",
			"7",
			"8",
			"9",
			"a",
			"b",
			"c",
			"d",
			"e",
			"f",
			"g",
			"h",
			"i",
			"j",
			"k",
			"l",
			"m",
			"n",
			"o",
			"p",
			"q",
			"r",
			"s",
			"t",
			"u",
			"v",
			"w",
			"x",
			"y",
			"z",
			"A",
			"B",
			"C",
			"D",
			"E",
			"F",
			"G",
			"H",
			"I",
			"J",
			"K",
			"L",
			"M",
			"N",
			"O",
			"P",
			"Q",
			"R",
			"S",
			"T",
			"U",
			"V",
			"W",
			"X",
			"Y",
			"Z"
		];
	if (num) {
		range = num;
	} else {
		range = 32;
	}
	for (var i = 0; i < range; i++) {
		var pos = Math.round(Math.random() * (arr.length - 1));
		str += arr[pos];
	}

	return str;
};

/****************************** http ******************************/
/** 获取请求头 */

export const getHeaders = (configHeader, method) => {
	var app = getApp();
	const token = getApp().globalData.userInfo
		? getApp().globalData.userInfo.token
		: null;
	var header = {
		"Content-Type": "application/json",
		Authorization: token ? `token ${token}` : ""
	};
	if (configHeader) {
		for (var key in configHeader) {
			header[key] = configHeader[key];
		}
	}
	return header;
};

/** GET请求 */
export const get = async config => {
	return await _request(config, "GET");
};

/** POST请求 */
export const post = async config => {
	return await _request(config, "POST");
};
/** PUT请求 */
export const put = config => {
	_request(config, "PUT");
};
//上传文件
export const uploadFile = config => {
	_uploadFile(config, "POST");
};
/** HTTP请求 */
export const _request = (config, method) => {
	return new Promise((resolve, reject) => {
		let headers = config.headers ? config.headers : {};
		let url = config.path;
		if (!config.isHiddeLoading) {
			uni.showLoading({
				title: "加载中...",
				mask: true
			});
		}
		uni.request({
			url: url,
			method: method,
			header: getHeaders(headers, method),
			data: config.params,
			dataType: config.dataType,
			success: res => {
				if (!config.isHiddeLoading) {
					uni.hideLoading();
				}
				console.log(url + " =====", config.params, res);
				// 调用成功回调函数
				if (res.data && res.statusCode == 200) {
					resolve(res.data);
				} else if (res.statusCode === 500) {
					toast("服务器连接异常，请重试");
				} else if (res.statusCode === 600) {
					toast("发送请求失败");
				} else if (res.statusCode === 404) {
					toast("服务器跑丢了~");
				}
			},
			fail: err => {
				if (!config.isHiddeLoading) {
					uni.hideLoading();
				}
				// 调用失败回调函数
				toast("服务器连接异常，请重试");
				reject(err);
			}
		});
	});
};

/*** 上传文件 ****/
export const _uploadFile = (config, method) => {
	var headers = config.headers ? config.headers : {};
	if (!config.isHiddeLoading) {
		uni.showLoading({
			title: "加载中...",
			mask: true
		});
	}
	uni.uploadFile({
		url: config.path,
		filePath: config.filePath,
		name: config.name,
		formData: config.formData,
		header: getHeaders(headers, method),
		method: method,
		success: function(res) {
			if (!config.isHiddeLoading) {
				uni.hideLoading();
			}
			console.log(config.path + " =====", config.params, res);
			// 调用成功回调函数
			if (config.success && typeof config.success === "function") {
				if (res.data && res.statusCode == 200) {
					if (res.data.code === 20001) {
						// 未登录
						getApp().globalData.userInfo = null;
						uni.navigateTo({
							url: "pages/login/loginPhone"
						});
					} else {
						config.success(res.data, "");
					}
				} else if (res.statusCode === 500) {
					toast("服务器连接异常，请重试");
				} else if (res.statusCode === 600) {
					toast("发送请求失败");
				} else if (res.statusCode === 404) {
					toast("服务器跑丢了~");
				}
			}
		},
		fail: function(res) {
			if (!config.isHiddeLoading) {
				uni.hideLoading();
			}
			// 调用失败回调函数
			if (config.fail && typeof config.fail === "function") {
				config.fail(res);
			}
		},
		complete: function() {
			if (config.complete && typeof config.complete === "function") {
				config.complete();
			}
		}
	});
};
/****************************** 数据校验 ******************************/
export const isEmpty = (str, minLength, maxLength) => {
	str = str.toString();
	minLength = minLength ? minLength : 1;
	maxLength = maxLength ? maxLength : 99999999;
	if (
		str == null ||
		str.trim().length < minLength ||
		str.trim().length > maxLength
	) {
		return true;
	}
	return false;
};

/**验证身份证姓名 */
export const checkIdCardName = name => {
	var reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{1,15}$/;
	return reg.test(name);
};

/**验证身份证号码 */
export const checkIdCardCode = code => {
	var reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
	if (reg.test(code)) {
		//校验码判断
		var c = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //系数
		var b = new Array(
			"1",
			"0",
			"X",
			"9",
			"8",
			"7",
			"6",
			"5",
			"4",
			"3",
			"2"
		); //校验码对照表
		var id_array = code.split("");
		var sum = 0;
		for (var k = 0; k < 17; k++) {
			sum += parseInt(id_array[k]) * parseInt(c[k]);
		}
		if (id_array[17].toUpperCase() == b[sum % 11].toUpperCase()) {
			return true;
		}
	}
	return false;
};

/**验证银行卡号码,检查银行卡(Luhm校验) 1、从卡号最后一位数字开始，逆向将奇数位(1、3、5等等)相加。
 * 2、从卡号最后一位数字开始，逆向将偶数位数字，先乘以2（如果乘积为两位数，则将其减去9），再求和。
 * 3、将奇数位总和加上偶数位总和，结果应该可以被10整除。 */
export const checkBankCardCode = code => {
	if (!isEmpty(code, 14, 24)) {
		var luhmSum = 0;
		var num = 0; //临时变量
		var index = 1; // 逆向后奇偶标志

		for (var i = code.length - 1; i >= 0; i--) {
			num = parseInt(code.substr(i, 1));
			if (index % 2 == 0) {
				num = num * 2 > 9 ? num * 2 - 9 : num * 2;
			}
			luhmSum += num;
			index++;
		}
		return luhmSum % 10 == 0;
	}
	return false;
};

/** 手机号校验，符合格式返回true，不符合返回false */
export const checkTel = tel => {
	var reg = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(16[0-9]{1})|(19[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
	return reg.test(tel);
};

/** 手机号校验，带提示，符合格式返回true，不符合返回false */
export const checkTelTip = tel => {
	if (isEmpty(tel)) {
		toast(cfg.msg.telEmpty);
		return false;
	}

	if (tel.trim().length != 11 || !checkTel(tel)) {
		toast(cfg.msg.telError);
		return false;
	}

	return true;
};

/** 密码校验，符合格式返回true，不符合返回false */
export const checkPwd = pwd => {
	var reg = new RegExp(/^([A-Za-z0-9]+)$/);
	var reg2 = new RegExp(/[A-Za-z]/);
	var reg3 = new RegExp(/[0-9]/);
	return reg.test(pwd) && reg2.test(pwd) && reg3.test(pwd);
};

/** 密码校验，带提示，符合格式返回true，不符合返回false */
export const checkPwdTip = pwd => {
	if (isEmpty(pwd)) {
		toast(cfg.msg.pwdEmpty);
		return false;
	}

	if (pwd.trim().length < 6 || pwd.trim().length > 12 || !checkPwd(pwd)) {
		toast(cfg.msg.pwdError);
		return false;
	}

	return true;
};

/** 验证码校验，符合格式返回true，不符合返回false */
export const checkCode = code => {
	return true;
};

/** 验证码校验，带提示，符合格式返回true，不符合返回false */
export const checkCodeTip = code => {
	if (isEmpty(code)) {
		toast(cfg.msg.codeEmpty);
		return false;
	}

	if (code.trim().length < 6 || !checkCode(code)) {
		toast(cfg.msg.codeError);
		return false;
	}

	return true;
};

/****************************** util ******************************/
/** 提示框，提示操作成功失败 */
export const toast = (msg, duration) => {
	uni.showToast({
		title: msg,
		mask: true,
		icon: "none",
		duration: duration || 1500
	});
};

/** 弹窗，确认结果 */
export const modal = (title, content) => {
	wx.showModal({
		title: title,
		content: content,
		showCancel: false,
		confirmColor: "#317EF3",
		confirmText: "我知道了"
	});
};

/** 绑定数据值 */
export const bindVal = (e, page, name) => {
	if (!page) {
		var pages = getCurrentPages();
		page = pages[pages.length - 1];
	}
	if (!name) {
		name = e.target.id;
	}

	var obj = {};
	obj[name] = e.detail.value;
	page.setData(obj);
};

/** 验证码倒计时 */
export const countDown = page => {
	var count = page.codeCount - 1;

	page.codeCount = count;
	page.codeText = `${count}s后重新发送`;

	if (page.codeCount < 1) {
		page.codeBtnDisabled = false;
		page.codeText = "获取验证码";
	} else {
		setTimeout(countDown, 1000, page);
	}
};

/**** 是不是Android系统*/
export const isAndroid = () => {
	var system = getApp().globalData.systemInfo.system;
	if (system.indexOf("Android") != -1) {
		// 安卓手机
		return true;
	} else {
		return false;
	}
};

/**** 随机生成UUID***/
export const uuid = () => {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
};
// 随机32位字符串
export const randomString = len => {
	len = len || 32;
	var $chars =
		"ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
	var maxPos = $chars.length;
	var pwd = "";
	for (var i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
};
// 证件隐藏 加*号
export const strPlusXing = (str, frontLen, endLen) => {
	var len = str.length - frontLen - endLen;
	var xing = "";
	for (var i = 0; i < len; i++) {
		xing += "*";
	}
	return str.substr(0, frontLen) + xing + str.substr(str.length - endLen);
};

// 取出数组中不同的元素
export const getArrDifference = (arr1, arr2) => {
	return arr1.concat(arr2).filter(function(v, i, arr) {
		return arr.indexOf(v) === arr.lastIndexOf(v);
	});
};
